<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;

class Filter extends Model
{
    protected $fillable = [
    	'store_id',
    	'filter_time',
	    'add_member',
	    'record_recharge',
	    'record_send',
	    'record_balance',
	    'record_order',
	    'record_goods',
	    'record_storage',
	    'record_take_away',
	    'record_storage_man',
	    'record_take_away_man',
	    'record_pay',
	    'purchase_to_material',
	    'goods_sell',
	    'record_room',
	    'staff_practice'
    ];
    
    public function createFilter()
    {
    	$time = Carbon::now();
    	// 2 < time < 3
	    //2 < time()
    	if ($time->setTime(1, 0, 0)->timestamp > time() || $time->setTime(3, 0, 0)->timestamp < time()) {
    	    Log::info('尚未到达统计时间');
    	    print_r('尚未到达统计时间'.PHP_EOL);
    	    //return false;
	    }
    	$time = time();

    	$store_id = Store::all()->pluck('name', 'id');
    	
    	foreach ($store_id as $k => $v) {
    	    $this->setFilter($time, $k);
	    }
    	$res = $this->setFilter($time);
    	return $res;
    }
    /**
     * 新增一条filter记录
     * @param $time|string:2020-12-12 00:00:00|int:1609430399
     * @return object App\Models\Filter
     */
    public function setFilter($time, $store_id = 0)
    {
        if(is_int($time)){
        	$time = $time - 24 * 60 * 60;
            $start = Carbon::createFromTimestamp($time);
            $end = Carbon::createFromTimestamp($time);
        }
        
        if(is_string($time)){
            $start = new Carbon($time);
            $start = Carbon::createFromTimestamp($start->timestamp - 24 * 60 * 60);
            $end = new Carbon($time);
            $end = Carbon::createFromTimestamp($end->timestamp - 24 * 60 * 60);
        }
        if (Env('APP_DEBUG')){
        	$timeBetween = [$start->startOfYear(), $end->endOfYear()];
        } else {
        	$timeBetween = [$start->startOfDay(), $end->endOfDay()];
        }

        $recordRecharge = Filter::recordRecharge($timeBetween);

        $data = [
        	'store_id' => $store_id,
			'filter_time' => Carbon::createFromTimestamp($time),
			'record_recharge' => Arr::get($recordRecharge, 3, 0),
			'record_send' => Arr::get($recordRecharge, 2, 0),
			'add_member' => Arr::get($recordRecharge, 1, 0),
			'record_balance' => Filter::recordBalance($timeBetween)->sum('price'),
			'record_order' => Filter::recordOrder($timeBetween)->count(),
			'record_goods' => Filter::recordGoods($timeBetween),
			'record_storage' => Filter::recordStorage($timeBetween)->sum('number'),
			'record_take_away' => Filter::recordStorage($timeBetween, 2)->sum('number'),
			'record_storage_man' => Filter::recordStorage($timeBetween)->count(),
			'record_take_away_man' => Filter::recordStorage($timeBetween, 2)->count(),
			'record_pay' => Filter::recordPay($timeBetween)->sum('price'),
			'purchase_to_material' => Filter::purchaseToMaterial($timeBetween)->sum('price'),
	        'material_sell' => Filter::materialSell($timeBetween),
			'goods_sell' => Filter::goodsSell($timeBetween),
			'record_room' => Filter::recordRoom($timeBetween)->count(),
	        'staff_practice' => Filter::staffPractice($timeBetween),
        ];
        //dd($data);
        //$res = $this->updateOrCreate(['filter_time' => $data['filter_time']], $data);
        $res = $this->create($data);
        //dd($data, $res);
    }

	static protected function recordPay($timeBetween, $store_id = 0)
	{
		$data = RecordPay::whereBetween('created_at', $timeBetween);
		if($store_id > 0){
			$data->where('store_id', $store_id);
		}
		$data->get(['id', 'pay_type', 'price', 'created_at']);
//		$data = RecordPay::whereBetween('created_at', $timeBetween)
//			->get(['id', 'pay_type', 'price', 'created_at']);
		
		return $data;
	}

	static protected function recordRecharge($timeBetween, $store_id = 0)
	{
		$data = RecordRecharge::whereBetween('created_at', $timeBetween);
		if($store_id > 0){
			$data->where('store_id', $store_id);
		}
		$data = $data->get(['id', 'type', 'price', 'created_at']);

		$recordRecharge = [];
		foreach ($data->groupBy('type') as $key => $value) {
        	$recordRecharge[$key] = $value->sum('price');
        }

		return $recordRecharge;
	}

	static protected function recordBalance($timeBetween, $store_id = 0)
	{
		$data = RecordBalance::whereBetween('created_at', $timeBetween)
			->where('type', '<>', '1');
		if($store_id > 0){
			$data->where('store_id', $store_id);
		}
			$data->get(['id','type', 'price', 'created_at']);
		return $data;
	}

	static protected function recordOrder($timeBetween, $store_id = 0)
	{
		$data = RecordOrder::with(['order' => function($q){
			$q->withTrashed()->selectRaw('id, status');
		}])->whereBetween('created_at', $timeBetween);
		if($store_id > 0){
			$data->where('store_id', $store_id);
		}
			$data->get(['id', 'store_id', 'order_id', 'price', 'created_at']);
		return $data;
	}

	static protected function recordGoods($timeBetween, $store_id = 0)
	{
		$where = ['style' => 2, 'type' => 2];
		if($store_id > 0){
			$where['store_id'] = $store_id;
		}
		$data = RecordGoods::whereBetween('created_at', $timeBetween)
			->where($where)
			->get(['id', 'goods_id', 'goods_sku_id', 'number']);

		return $data->sum('number');
	}

	static protected function recordStorage($timeBetween, $type = 1, $store_id = 0)
	{
		$where = ['type' => $type];
		if($store_id > 0){
			$where['store_id'] = $store_id;
		}
		$data = RecordStorage::whereBetween('created_at', $timeBetween)
			->where($where)
			->get(['id', 'name', 'number', 'goods_id', 'goods_sku_id']);
		return $data;
	}

	static protected function purchaseToMaterial($timeBetween, $store_id = 0)
	{
		$data = PurchaseToMaterial::whereBetween('created_at', $timeBetween)
				->with(['recordmaterial' => function($q){
					$q->where('type', 1);// 1采购2消耗
				}])
			    ->selectRaw('Month(created_at) as date, sum(unit_price * number) as price')
				->groupBy('date');
		if($store_id > 0){
			$data->where('store_id', $store_id);
		}
		$data = $data->get();

		return $data;
	}

	static protected function recordRoom($timeBetween, $store_id = 0)
	{
		$data = RecordOrder::whereBetween('created_at', $timeBetween)
			->with(['order' => function ($q) {
				$q->whereNotIn('status', [1, 5]);
			}]);
		if($store_id > 0){
			$data->where('store_id', $store_id);
		}
		$dat = $data->get(['id']);
		return $data;
	}
	static protected function materialSell($timeBetween, $store_id = 0)
	{
		$where = ['style' => 2, 'type' => 2];
		if($store_id > 0){
			$where['store_id'] = $store_id;
		}
		$data = RecordMaterial::whereBetween('created_at', $timeBetween)
			->with(['getUnitPrice' => function($q){
				$q->selectRaw('id,unit_price');
		}])
			->where($where)
			->get(['id', 'purchase_to_material_id', 'number', 'style', 'type'])->toArray();
		
		$data = collect($data);
		$price = 0;
		$data->map(function ($item) use (&$price){
			if(isset($item['get_unit_price']['unit_price'])){
				$price += $item['get_unit_price']['unit_price'] * $item['number'];
			}
		});

		return $price;
	}

	static protected function goodsSell($timeBetween, $store_id = 0)
	{
		$where = ['style' => 2, 'type' => 2];
		if($store_id > 0){
			$where['store_id'] = $store_id;
		}
		$data = RecordGoods::whereBetween('created_at', $timeBetween)
			->with(['goods' => function ($q) {
				$q->withTrashed()->selectRaw('id,price');
			}])
			->where($where)
			->get(['id', 'goods_id', 'goods_sku_id', 'number']);
		
		$goods = [];
		foreach ($data->where('goods_sku_id', '')->groupBy('goods_id') as $k => $v) {
			//static $goods = [];
			$goods[$k] = 0;
			$v->map(function ($item) use (&$goods, $k) {
				if(isset($item->number)){
					$goods[$k] += $item->number * $item->goods->price;
				}
			});
		}
		
		$goodsSku = [];
		foreach ($data->groupBy('goods_sku_id') as $k => $v)
		{
			//static $goodsSku = [];
			if($k !== ''){
				$goodsSku[$k] = 0;
				$v->map(function ($item) use (&$goodsSku, $k) {
					if(isset($item->number)){
						$goodsSku[$k] += $item->number * $item->goods->price;
					}
				});
			}
		}
		//dd($data);
		$data = [collect($goods)->sum(), collect($goodsSku)->sum()];
		$data = collect($data);
		return $data->sum();
	}
	static protected function staffPractice($timeBetween, $store_id = 0)
	{
		$res = RecordStaffPractice::whereBetween('staff_practice_time', $timeBetween);
		
		if($store_id > 0){
			$res->where('store_id', $store_id);
		}
		$res = $res->get(['price']);
		return $res->sum('price');
	}
}
